package com.zaofan.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @FileName UserFilter.java
 * @description UserFilter表示用户登录验证过滤器
 * @author sf
 * @version 1.0.0
 * @since 2015-01-16
 */
public class UserFilter implements Filter {

	/**
	 * 跳转错误页面地址
	 */
	private String error_page;

	/**
	 * 用户登录不进行验证地址
	 */
	private List<String> notCheckURLList = new ArrayList<String>();

	/**
	 * 登录验证
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		resp.setContentType("text/html;");
		resp.setCharacterEncoding("utf-8");
		
		HttpSession session = req.getSession();
		
		String ctxPath = req.getContextPath();// 得到web应用程序的上下文路径
		String request_uri = req.getRequestURI().substring(ctxPath.length());// 得到用户请求的URI
		
		if (session.getAttribute("userinfo") != null) {// 验证登录是否超时
			chain.doFilter(request, response);
			return;
		} else {
			for(String url : notCheckURLList){
                if (request_uri.contains(url)){
                    chain.doFilter(request, response);
                    return;
                }
            }
//            if (req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
//                PrintWriter printWriter = response.getWriter();
//                JsonPersistence jp = JsonFactory.instance();
//                Map<String,Object> map = new HashMap<>();
//                map.put("sessionState",0);
//                printWriter.print(jp.json(map));
//                printWriter.flush();
//                printWriter.close();
//                return;
//            }

            resp.getWriter().print("<script language=\"javaScript\">" + "location.href='"+ ctxPath + error_page + "';" + "</script>");
		}
	}

	/**
	 * 过滤器上下文初始化
	 */
	public void init(FilterConfig filterConfig) throws ServletException {

		error_page = filterConfig.getInitParameter("ERROR_URI");// 获取错误页面跳转地址

		String notCheckURLListStr = filterConfig.getInitParameter("NOT_VALIDATE_URI");// 获取不进行验证的访问地址

		if (notCheckURLListStr != null) {
			String[] str = notCheckURLListStr.split(",");
			for (int i = 0; i < str.length; i++) {
				notCheckURLList.add(str[i]);
			}
		}
		notCheckURLList.add("/home/chooseCity.do");

		if (error_page == null || error_page == "") {
			throw new ServletException("没有找到登录超时跳转页");
		}

	}

	public void destroy() {

	}
}
